package model

import (
	"common/helper"
	"fmt"
	g "github.com/doug-martin/goqu/v9"
	"time"
)

type RateListData struct {
	D []TblRatelist `json:"d"`
}

// 手续费配置表
type TblRatelist struct {
	Id          int     `db:"id" json:"id"`
	Ty          uint32  `db:"ty" json:"ty"`                     //类型 0充值 1下发
	Rate        float64 `db:"rate" json:"rate"`                 //手续费率 %
	Min         float64 `db:"min" json:"min"`                   //最少收取
	Max         float64 `db:"max" json:"max"`                   //最高收取
	UpdatedAt   uint32  `db:"updated_at" json:"updated_at"`     //修改时间
	UpdatedName string  `db:"updated_name" json:"updated_name"` //修改人
}

func RateListList() (RateListData, error) {

	data := RateListData{}
	query, _, _ := dialect.From("tbl_rate_config").Select(colsRateList...).ToSQL()
	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	return data, nil
}

func RateListUpdate(adminName string, id int, ty uint32, rate, min, max float64) error {

	updateData := TblRatelist{
		Id:          id,
		Ty:          ty,
		Rate:        rate,
		Min:         min,
		Max:         max,
		UpdatedAt:   uint32(time.Now().Unix()),
		UpdatedName: adminName,
	}
	query, _, _ := dialect.Update("tbl_rate_config").Set(&updateData).Where(g.Ex{"id": id}).ToSQL()
	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	var data []TblRatelist
	query, _, _ = dialect.From("tbl_rate_config").Select(colsRateList...).Where(g.Ex{"id": id}).ToSQL()
	err = meta.MerchantDB.Select(&data, query)
	if err != nil {
		return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	key := "finance:fee:rate"
	pipe := meta.MerchantRedis.Pipeline()
	defer pipe.Close()

	pipe.Del(ctx, key)
	for _, v := range data {
		b, _ := helper.JsonMarshal(v)
		pipe.HSet(ctx, key, v.Ty, string(b))
	}
	_, _ = pipe.Exec(ctx)

	return nil
}
